package com.zsgeek.wisdchain.qutu.view.home;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.zsgeek.wisdchain.qutu.R;
import com.zsgeek.wisdchain.qutu.base.customControl.ColorFlipPagerTitleView;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequest;
import com.zsgeek.wisdchain.qutu.base.http.JsonRequestCallBack;
import com.zsgeek.wisdchain.qutu.base.model.GetPartListModel;
import com.zsgeek.wisdchain.qutu.popup.dialog.DialogUtil;
import com.zsgeek.wisdchain.qutu.tools.TextUtils;
import com.zsgeek.wisdchain.qutu.tools.ToastHelper;
import com.zsgeek.wisdchain.qutu.tools.UrlPathHelper;
import com.zsgeek.wisdchain.qutu.view.BaseFragment;
import com.zsgeek.wisdchain.qutu.view.find.RecommendFragment;
import com.zsgeek.wisdchain.qutu.view.find.SearchActivity;
import com.zsgeek.wisdchain.qutu.view.home.adapter.HomePagerAdapter;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 发现
 * <p/>
 */
public class FindFragment extends BaseFragment {
    @BindView(R.id.title_tv)
    TextView title_tv;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    private List<GetPartListModel.DataBean> orderManagementTitles = new ArrayList<>();
//    private List<String> searchHistoryList = new ArrayList<>();

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_find;
    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarColorTransformEnable(false)
                .statusBarDarkFont(true, 0.9f)
//                .statusBarDarkFont(true, 0.2f)
                .init();
    }

    @Override
    protected void initView(View view) {

    }

    @Override
    protected void initData() {
        getPartList();
    }

    @OnClick({R.id.title_tv})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_tv:
                startActivity(new Intent(getActivity(), SearchActivity.class));
//                SearchShowDialog();
                break;
        }
    }

    /**
     * 2、标题栏接口
     */
    private void getPartList() {
        DialogUtil.createLoadingDialog(getActivity(), null);
        new JsonRequest(new JsonRequestCallBack() {
            @Override
            public void showResult(Object object, String taskId) {
                if (object instanceof GetPartListModel) {
                    GetPartListModel dataModel = (GetPartListModel) object;
                    DialogUtil.closeLoadingDialog(getActivity());
                    if (dataModel.getCode() == 2000) {
                        List<GetPartListModel.DataBean> data = dataModel.getData();
                        if (TextUtils.isEmpty(data)) {
                            orderManagementTitles.add(new GetPartListModel.DataBean(0, "推荐", "推荐", 1, 1, "2019-09-27T13:02:41.000+0000"));
                        } else orderManagementTitles.addAll(data);

                        viewpager.setAdapter(new HomePagerAdapter(getFragmentManager(), getFragments()));
                        viewpager.setOffscreenPageLimit(1);
                        initMagicIndicator();
                    } else ToastHelper.showToast(dataModel.getMessage());
                }
            }

            @Override
            public void showError(String errorMsg, String taskId) {
                DialogUtil.closeLoadingDialog(getActivity());
                ToastHelper.showToast(errorMsg);
            }
        }).postJson(UrlPathHelper.getAdver() + "adver/getPartList", true, null, GetPartListModel.class);
    }

//    private void SearchShowDialog() {
//        new SYDialog.Builder(getActivity())
//                .setDialogView(R.layout.fragment_find_search_dialog)
//                .setWindowBackgroundP(0.5f)
//                .setAnimStyle(R.style.AnimUp)
//                .setCancelableOutSide(true)
//                .setBuildChildListener((dialog, view, layoutRes) -> {
//
//                    ClearEditText searchEt = view.findViewById(R.id.search_bottom_tv);
//                    searchEt.setOnEditorActionListener((v, actionId, event) -> {
//                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                            String key = searchEt.getText().toString().trim();
//                            if (TextUtils.isEmpty(key)) {
//                                ToastHelper.showToast("请输入内容");
//                                return true;
//                            }
//                            //  业务逻辑
//                            queryAdverList(key);
//                            //  键盘隐藏
//                            Utils.CloseInoutDecorView(getActivity());
//                            title_tv.setText(key);
//                            dialog.dismiss();
//                            return true;
//                        }
//                        return false;
//                    });
//                    View list_date_emptyView = view.findViewById(R.id.list_date_emptyView);
//                    SmartRefreshLayout refreshLayout = view.findViewById(R.id.refreshLayout);
//                    EmptyRecyclerView recyclerView = view.findViewById(R.id.recyclerView);
//                    view.findViewById(R.id.cancel_tv).setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//                            dialog.dismiss();
//                        }
//                    });
//
//                    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//                    recyclerView.addItemDecoration(new LinearLayoutColorDivider(this.getResources(),
//                            R.color.transparent, R.dimen.zero, LinearLayoutManager.VERTICAL));
//                    recyclerView.setEmptyView(list_date_emptyView);
//                    recyclerView.setAdapter(mAdapter);
//                    mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//                        @Override
//                        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//                            startActivityForResult(new Intent(getActivity(), FindDetailsActivity.class)
//                                    .putExtra("data", searchHistoryList.get(position)), 0x100);
//                        }
//                    });
//                    initRefreshLayout(refreshLayout);
//                })
//                .setScreenWidthP(1.0f)
//                .setGravity(Gravity.FILL_VERTICAL).show();
//    }
//
//    /**
//     * 搜索广告接口
//     */
//    private void queryAdverList(String key) {
//        DialogUtil.createLoadingDialog(getActivity(), null);
//        new JsonRequest(new JsonRequestCallBack() {
//            @Override
//            public void showResult(Object object, String taskId) {
//                if (object instanceof QueryAdverListModel) {
//                    QueryAdverListModel dataModel = (QueryAdverListModel) object;
//                    DialogUtil.closeLoadingDialog(getActivity());
//                    if (dataModel.getCode() == 2000) {
//                        ToastHelper.showToast("搜索成功");
//                    } else ToastHelper.showToast(dataModel.getMessage());
//                }
//            }
//
//            @Override
//            public void showError(String errorMsg, String taskId) {
//                DialogUtil.closeLoadingDialog(getActivity());
//                ToastHelper.showToast(errorMsg);
//            }
//        }).postJson(UrlPathHelper.getAdver() + "adver/queryAdverList?label=" + key, true, null, QueryAdverListModel.class);
//    }

    private ArrayList<Fragment> getFragments() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        for (int i = 0; i < orderManagementTitles.size(); i++) {
            fragments.add(new RecommendFragment(orderManagementTitles.get(i).getId()));
        }
        return fragments;
    }

    private void initMagicIndicator() {
        CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setScrollPivotX(0.65f);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return orderManagementTitles == null ? 0 : orderManagementTitles.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ColorFlipPagerTitleView(context);
                simplePagerTitleView.setText(orderManagementTitles.get(index).getTitle());
                simplePagerTitleView.setNormalColor(ContextCompat.getColor(getActivity(), R.color.color_999999));
                simplePagerTitleView.setSelectedColor(ContextCompat.getColor(getActivity(), R.color.color_333333));
                simplePagerTitleView.setTextSize(15);
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewpager.setCurrentItem(index, true);
                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setLineHeight(UIUtil.dip2px(context, 3));
                indicator.setLineWidth(UIUtil.dip2px(context, 21));
//                indicator.setBackgroundResource(R.mipmap.rounded_rectangle_select_blue_bg);
                indicator.setBackgroundColor(getResources().getColor(R.color.white));
                indicator.setColors(ContextCompat.getColor(getActivity(), R.color.color_C26CFD));
                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(magicIndicator, viewpager);

        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                magicIndicator.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                magicIndicator.onPageSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                magicIndicator.onPageScrollStateChanged(state);
            }
        });

        viewpager.setCurrentItem(0);
    }

//    private BaseQuickAdapter<String, BaseViewHolder> mAdapter =
//            new BaseQuickAdapter<String, BaseViewHolder>(R.layout.fragment_find_search_item, searchHistoryList) {
//                @Override
//                protected void convert(BaseViewHolder baseViewHolder, final String dataBean) {
////                    baseViewHolder.setText(R.id.currency_tv, dataBean.getCoinName());
////                    baseViewHolder.setText(R.id.amount_tv, dataBean.getCoinAddress());
//                }
//            };

//    private void initRefreshLayout(SmartRefreshLayout refreshLayout) {
//        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
////                getDevice();
//            }
//        });
//    }
//
//    private void stopRefresh(SmartRefreshLayout refreshLayout) {
//        refreshLayout.finishRefresh();
//        refreshLayout.resetNoMoreData();
//    }
}
